//
//  HJAudioPlayer.m
//  HMusicPlayer
//
//  Created by hament deng on 14/10/31.
//  Copyright (c) 2014年 HJ. All rights reserved.
//

#import "HJAudioPlayer.h"
#import "HSongItem.h"
#import "HPlaylistItem.h"
#import "HSQLManager.h"
#import "HMainWC.h"
#import "HCoreConfig.h"
#import "HPlayListView.h"

#import <OrigamiEngine/ORGMEngine.h>
#import "DOUAudioStreamer.h"
#import "DOUAudioStreamer+Options.h"



//dou streamer 用到的监听的key
static void *kStatusKVOKey = &kStatusKVOKey;
static void *kDurationKVOKey = &kDurationKVOKey;
static void *kBufferingRatioKVOKey = &kBufferingRatioKVOKey;



@implementation HJAudioPlayer


static HJAudioPlayer * hplayer=nil;
+(HJAudioPlayer*)sharePlayer{
    @synchronized(self) {
        if (hplayer==nil) {

            hplayer=[[HJAudioPlayer alloc] init];

            hplayer.playListID=@"";
            hplayer.currentPlaySongItem=nil;
            hplayer.currentPlayMode=1;//初始化为顺序播放 // 1 :顺序  2:循环  3:随机 4.单曲循环
            [hplayer readInfoFromlastSetting];//从上次保存的信息读取
            

            
            
            
        }
        
    }
    return hplayer;
}


-(id)init {
    self=[super init];
    if (self) {
        
        //dou streamer 注册
//        [DOUAudioStreamer setOptions:[DOUAudioStreamer options] | DOUAudioStreamerRequireSHA256];
        [DOUAudioStreamer setOptions:[DOUAudioStreamer options]];
        //初始化无损音频引擎
        self.orgmenginePlayer=[[ORGMEngine alloc] init];
        self.currentUsePlayerType=ORGMEngineType;//默认为orgmi
        self.volume=[NSNumber numberWithFloat:1.0f];
    }

    return self;
}

#pragma mark ----------lazyloading--------
-(NSMutableArray *) currentSongsQueue {
    
    
    if (!_currentSongsQueue) {
        _currentSongsQueue=[[NSMutableArray alloc] initWithCapacity:10];
        
    }
    
    return _currentSongsQueue;
}




-(NSMutableDictionary*)hadPlayRandomDic {
    
    if (!_hadPlayRandomDic) {
        _hadPlayRandomDic=[NSMutableDictionary dictionaryWithCapacity:10];
    }
    
    return _hadPlayRandomDic;
}

-(void)setDelegate:(HMainWC *)delegate {
    _delegate=delegate;
    _orgmenginePlayer.delegate=_delegate;

}




#pragma mark ----------DOU audiostreamer相关-------

#pragma mark stopStreamer
- (void)stopStreamer
{
    if (self.streamPlayerer != nil) {
        [ self.streamPlayerer pause];
        [ self.streamPlayerer removeObserver:self forKeyPath:@"status"];
        [ self.streamPlayerer removeObserver:self forKeyPath:@"duration"];
       // [ self.streamPlayerer removeObserver:self forKeyPath:@"bufferingRatio"]; //网速,数据缓存等信息
         self.streamPlayerer = nil;
    }
}


#pragma mark updateStreamer
- (void)updateStatus
{
    switch ([ self.streamPlayerer status]) {
        case DOUAudioStreamerPlaying:
        {
            [self.delegate engine: self.streamPlayerer didChangeState:ORGMEngineStatePlaying];
            
        }
           
            break;
            
        case DOUAudioStreamerPaused:
        case DOUAudioStreamerIdle:
        {
            
        [self.delegate engine: self.streamPlayerer didChangeState:ORGMEngineStatePaused];
        
        }
            break;
            
        case DOUAudioStreamerFinished:   {
            [self.delegate engine: self.streamPlayerer didChangeState:ORGMEngineStateStopped];
            
            [self.delegate handleNextSongForStreamerPlayer];
            
        }
           
            break;
            
        case DOUAudioStreamerBuffering:
           
            break;
            
        case DOUAudioStreamerError:
        {
            
            [self.delegate engine: self.streamPlayerer didChangeState:ORGMEngineStateError];
        }
            
            break;
    }
}

#pragma mark doustreamer time update
-(void)timerAction{



}


#pragma mark ----------基类/嫁接 方法,公有动作-------

-(void)playSongWithSongItem:(HSongItem*)songitem{

    
    
    if(!songitem) return;
    
   //检测是否属于无损格式
   BOOL islossless =[HCoreConfig checkLosslessWithSongItem:songitem];
    //islossless=YES;
    
    [self stopStreamer];
    
    
    //播放前,先打开bookmark if need
    BOOL opensuccess=[HCoreConfig openFilesAccessingSecurityScopedWithSongItem:songitem];
    
    //文件权限
    if (opensuccess==NO) {
        
        [HCoreConfig alertWithTitle:NSLocalizedString(@"The song is unreadable", nil) window:[HMainWC shareWc].window];
        return;
    }
    
    //无损使用 Origamengine
    if(islossless) {
    
        self.currentUsePlayerType=ORGMEngineType;//
        
        if (self.orgmenginePlayer.currentState != ORGMEngineStatePlaying) {
            [self.orgmenginePlayer playUrl:songitem.audioFileURL];
        } else {
            [self.orgmenginePlayer setNextUrl:songitem.audioFileURL withDataFlush:YES];
        }

    }
    //一般的使用 streamer
    else {
    
        
        //stop orgmenginePlayer
        if (self.orgmenginePlayer.currentState != ORGMEngineStateStopped) {
            [self.orgmenginePlayer stop];
        }
        
        
        
        self.currentUsePlayerType=DOUAudioType;//
        
        
         self.streamPlayerer = [DOUAudioStreamer streamerWithAudioFile:songitem];
        [ self.streamPlayerer addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:kStatusKVOKey];
        [ self.streamPlayerer addObserver:self forKeyPath:@"duration" options:NSKeyValueObservingOptionNew context:kDurationKVOKey];
//        [_streamer addObserver:self forKeyPath:@"bufferingRatio" options:NSKeyValueObservingOptionNew context:kBufferingRatioKVOKey];
        [self.streamPlayerer setVolume:[self.volume floatValue]];//音量
        [ self.streamPlayerer play];

    
    
    
    }



}



-(void)playAction{

    if (self.currentUsePlayerType==ORGMEngineType) {
        
        
    } else if (self.currentUsePlayerType==DOUAudioType) {
    
    
    
    }
    
}


-(void)pauseAction{


    if (self.currentUsePlayerType==ORGMEngineType) {
        
        
    } else if (self.currentUsePlayerType==DOUAudioType) {
        
        
        
    }
    
}



-(void)resumeAction{

    if (self.currentUsePlayerType==ORGMEngineType) {
        
        
        
        
        
    } else if (self.currentUsePlayerType==DOUAudioType) {
        
        
        
    }
    
    
}


-(void)stopAction{

    if (self.currentUsePlayerType==ORGMEngineType) {
        
        
        
        [self.orgmenginePlayer stop];
        
    } else if (self.currentUsePlayerType==DOUAudioType) {
        
         [self.streamPlayerer stop];
    }



}

//0.0~1.0
-(void)seekToTimeWithFloatValue:(float)value{

    
    HSongItem* song= self.currentPlaySongItem;
    
    
    if (song) {
        
        if (self.currentUsePlayerType==ORGMEngineType) {
            float time=value*(song.songDuration/1000);
            //设置音量UI
            [self.orgmenginePlayer seekToTime:time withDataFlush:YES];

            
        } else if (self.currentUsePlayerType==DOUAudioType) {
            
            
            [self.streamPlayerer setCurrentTime:[self.streamPlayerer duration] * value];
        }
        
        
    } else {
        
        if (self.currentUsePlayerType==ORGMEngineType) {
            
            [self.orgmenginePlayer seekToTime:0.0f];
            
        } else if (self.currentUsePlayerType==DOUAudioType) {
            
            [self.streamPlayerer setCurrentTime:0.0f];
            
        }
    }

    
    

    

}


//0.0~1.0
-(void)setVolumeWithFloatValue:(float)value{

    self.volume=[NSNumber numberWithFloat:value];
    //音量是共用的
    
    [self.orgmenginePlayer setVolume:value*100.0f];
 
   //if (self.streamPlayerer) {
        
       [self.streamPlayerer setVolume:value];
       
    //}

}



#pragma mark 清空当前播放队列
-(void)emptyCurrentPlayQueue{

//停止播放
    if (self.currentUsePlayerType==ORGMEngineType) {
        if(self.orgmenginePlayer.currentState==ORGMEngineStatePlaying ||self.orgmenginePlayer.currentState==ORGMEngineStatePaused) {
            [self stopAction];
        }
        
    } else if (self.currentUsePlayerType==DOUAudioType){
        
        if([self.streamPlayerer status]==DOUAudioStreamerPlaying || [self.streamPlayerer status]==DOUAudioStreamerPaused){

            [self stopAction];
            
        }

    }
    
    [self closeBookmarWithCurrentItem];
   [self.currentSongsQueue removeAllObjects];
   [self.hadPlayRandomDic removeAllObjects];
    self.currentPlaySongItem=nil;
    self.playListID=@"";
    
}


#pragma mark ------监听-------

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if (context == kStatusKVOKey) {
        [self performSelector:@selector(updateStatus)
                     onThread:[NSThread mainThread]
                   withObject:nil
                waitUntilDone:NO];
    }
    else if (context == kDurationKVOKey) {
                [self performSelector:@selector(timerAction)
                             onThread:[NSThread mainThread]
                           withObject:nil
                        waitUntilDone:NO];
    }
    else if (context == kBufferingRatioKVOKey) {
//        [self performSelector:@selector(_updateBufferingStatus)
//                     onThread:[NSThread mainThread]
//                   withObject:nil
//                waitUntilDone:NO];
    }
    else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}





#pragma mark ----------业务逻辑--------

#pragma mark 读取上次的保存信息
-(void)readInfoFromlastSetting{
    @autoreleasepool {
        NSDictionary * dic= [[NSUserDefaults standardUserDefaults] valueForKey:HCurrentPlayInfo];
        if(dic){
            NSNumber * vol= (NSNumber*)dic[HVolume];
            NSNumber * pm= (NSNumber*)dic[HPlayMode];
            self.volume=vol;
            self.currentPlayMode=pm.integerValue;//初始化为顺序播放 // 1 :顺序  2:循环  3:随机 4.单曲循环
            //self.playListID=dic[HPlaylistID];//上次的播放列表
            
        }
    }
    
}



#pragma mark 初始化队列,播放歌曲,一般用于双击动作
-(void)configWithSongList:(NSArray*)songList playSongItem:(HSongItem*)songitem{
    
    
    //清空队列,随机字典表
    [self.currentSongsQueue removeAllObjects];
    [self.hadPlayRandomDic removeAllObjects];
    
    //当前播放列表的id
    self.playListID=songitem.playListSyncID;
    
    //记录当前的播放列表的syncid
    self.currentPlaySongItem=songitem;
    [self.currentSongsQueue addObjectsFromArray:songList];
 
}


#pragma mark 当原播放列表有歌曲更新时候,更新当前播放队列
-(void)updateSongQueueWithSongsArr:(NSMutableArray*)songsArr{

    if([songsArr count]==0) return;
    
    //清空队列,随机字典表
    [self.currentSongsQueue removeAllObjects];
    [self.hadPlayRandomDic removeAllObjects];

    [self.currentSongsQueue addObjectsFromArray:songsArr];
    
    //重新定位currentSongitem
    HSongItem * csongitem=self.currentPlaySongItem;
    
    if (csongitem) {
        HSongItem * rsongitem=nil;
        for (HSongItem * songItem in songsArr) {
            
             // debugLog(@"csongitem:%@ ,songItem:%@",csongitem.syncid,songItem.syncid);
            
            if ([csongitem.syncid isEqualToString:songItem.syncid]) {
               // debugLog(@"find ,id:%@ ,name:%@",songItem.syncid,songItem.songName);
                rsongitem=songItem;
                break;
            }
        }
        self.currentPlaySongItem=rsongitem;
    }else {
        self.currentPlaySongItem=[self.currentSongsQueue objectAtIndex:0];
    
    }


    //debugLog(@"play queue count:%d",[self.currentSongsQueue count]);
}


#pragma mark 当文件或id3tag修改时,需要更新队列
-(void)updateQueueSongName:(NSString*)name path:(NSString*)newpath oldPath:(NSString*)oldpath{

    for (HSongItem * songitem in self.currentSongsQueue) {
        NSString * localPath=CHECKSTR(songitem.localPath);
        if([localPath isEqualToString:oldpath]){
            songitem.songName=name;
            songitem.localPath=newpath;
            break;
        }
    }
}



#pragma mark 打开/关闭当前歌曲的bookmark


#pragma mark 关闭当前歌曲的bookmark
-(void)openBookmarWithCurrentItem{
    
    if(self.currentPlaySongItem){
        
        [HCoreConfig openFilesAccessingSecurityScopedWithSongItem:self.currentPlaySongItem];
        
    }
    
    
}

-(void)closeBookmarWithCurrentItem{

    if(self.currentPlaySongItem){

        [HCoreConfig stopFilesAccessingSecurityScopedWithSongItem:self.currentPlaySongItem];
    
    }


}


#pragma mark 上一首/下一首按钮
-(HSongItem*)getNextSongItemWithActionIsNext:(BOOL)flag{
    
    //1.先判断队列是否有歌
    if (self.currentSongsQueue.count==0) {
        return nil;
    }
    
    
    //2.如果队列有歌曲,但当前没有播放歌曲,默认返回队列第一首
    if (!self.currentPlaySongItem) {
        self.currentPlaySongItem=self.currentSongsQueue[0];
        //清空一下随机队列
        [self.hadPlayRandomDic removeAllObjects];
        return self.currentPlaySongItem;
    }
    
    
    //清空一下随机队列,next/prev 都会破坏随机队列
    [self.hadPlayRandomDic removeAllObjects];
    
    NSUInteger currentSongindex=[self indexWithItem:self.currentPlaySongItem];
    
    //如果某种不知名的原因没法找到,返回队列第一首歌曲
    if(currentSongindex==NSNotFound) {
        
        self.currentPlaySongItem=self.currentSongsQueue[0];
        
        return self.currentPlaySongItem;
    }
    
    
    
    
    NSUInteger queuecount=[self.currentSongsQueue count];
    NSInteger songindex=0;
    
    
    
    //next
    if(flag) {
        songindex=currentSongindex+1;
        if(songindex>(queuecount-1)) {
            songindex=0;
        }
    }
    //pre
    else {
        songindex=currentSongindex-1;
        if(songindex<0) {
            songindex=(queuecount-1);//最后一首
        }
        
    }
    
    
    self.currentPlaySongItem=[self.currentSongsQueue objectAtIndex:songindex];
    
    return self.currentPlaySongItem;
}


//根据object返回index
-(NSUInteger)indexWithItem:(HSongItem*)songItem{
    
    NSUInteger index=[self.currentSongsQueue indexOfObject:songItem];
    
    return index;
    
}


#pragma mark 根据当前播放模式得出下一首歌曲
-(HSongItem*)theNextSongItem{
    
    
    NSUInteger queuecount=[self.currentSongsQueue count];
    
    if (queuecount==0) {
        return nil;
    }
    
    
    HSongItem * returnItem=nil;
    NSUInteger currentSongindex=[self indexWithItem:self.currentPlaySongItem];
    NSInteger songindex=0;
    
    // 1 :顺序  2:循环  3:随机 4.单曲循环
    switch (self.currentPlayMode) {
        case 1:
        {
            
            songindex=currentSongindex+1;
            if(songindex<=(queuecount-1)) {
                returnItem=[self.currentSongsQueue objectAtIndex:songindex];
            }
            
        }
            break;
        case 2:
        {
            
            songindex=currentSongindex+1;
            if(songindex>(queuecount-1)) {
                
                songindex=0;
            }
            returnItem=[self.currentSongsQueue objectAtIndex:songindex];
            
            
            
        }
            break;
            //随机
        case 3:
        {
            //把当前的歌曲加入播放队列
            [self.hadPlayRandomDic setObject:self.currentPlaySongItem.syncid forKey:self.currentPlaySongItem.syncid];
            
            @autoreleasepool {
                
                
                //先产生一个随机数组
                NSMutableArray * ranrar=[NSMutableArray arrayWithCapacity:queuecount];
                for (int i=0; i<queuecount; i++) {
                    NSNumber * num=[NSNumber numberWithInt:i];
                    [ranrar addObject:num];
                }
                
                //对数组排序打乱
                for (int i=0; i<queuecount; i++) {
                    int randInt = arc4random() %queuecount;
                    [ranrar exchangeObjectAtIndex:i withObjectAtIndex:randInt];
                }
                
                for(NSNumber * index in ranrar) {
                    
                    HSongItem * sonbig=[self.currentSongsQueue objectAtIndex:index.intValue];
                    
                    if(![self.hadPlayRandomDic objectForKey:sonbig.syncid]){
                        
                        returnItem=sonbig;
                        break ;
                    }
                    
                    
                }
                
            }
            
            
            if (returnItem) {
                [self.hadPlayRandomDic setObject:returnItem.syncid forKey:returnItem.syncid];
            }
            //如果队列已经播放完毕
            else {
                
                
            }
            
            
            
            
        }
            break;
            //单曲
        case 4:
        {
            
            returnItem= self.currentPlaySongItem;
            
        }
            break;
        default:
            break;
    }
    
    
    
    return returnItem;
}

#pragma mark 重命名时更改name和path
-(void)renameWithSongItem:(HSongItem*)theNewsongIOtem{}


#pragma mark delete songitems in play queue
-(void)deleteWithSongItems:(NSArray*)dSongitems fromItunes:(BOOL)flag{
    
    // debugLog(@"queue count:%d, dsongItems:%d",self.currentSongsQueue.count,dSongitems.count);
    
    if(self.currentSongsQueue.count==0 || dSongitems.count==0) {
        return;
    }
    
    //如果是itunes的比较localpath
    NSString * compareKey=@"localPath";
    
    //不是itunes的话比较播放列表
    if (!flag) {
        compareKey=@"syncid";//
    }
    
    int index=0;
    NSMutableIndexSet * indexset=[NSMutableIndexSet indexSet];
    for (HSongItem * songItem in self.currentSongsQueue) {
        for (HSongItem * deleteSongItem  in dSongitems){
            
            NSString * obj1=[songItem valueForKey:compareKey];
            NSString * obj2=[deleteSongItem valueForKey:compareKey];
            
            if([obj1 isEqualToString:obj2]) {
                //debugLog(@"obj1:%@",obj1);
                // debugLog(@"obj2:%@",obj2);
                [indexset addIndex:index];
            }
        }
        
        index++;
    }
    
    
    
    //如果删除的歌曲与当前队列相关
    if (indexset.count>0) {
        
        [self.currentSongsQueue removeObjectsAtIndexes:indexset];
    }
    
    
}




#pragma mark sort songqueue
-(void)sortTheSongQueue{

    if (self.currentSongsQueue.count==0) {
        
        return;
    }
    
    
    //清空一下随机队列,next/prev 都会破坏随机队列
    [self.hadPlayRandomDic removeAllObjects];
    
    
    
    
    NSArray * sortSonglyarr;
    
    //根据排序获取
    if ([[HCoreConfig shareConfig].currentSortType isEqualToString:SortByName]) {
        
        sortSonglyarr= [self.currentSongsQueue sortedArrayUsingComparator:^(HSongItem * obj1 ,HSongItem* obj2) {
            if ([obj1.songName compare:obj2.songName]==NSOrderedAscending)
                return  NSOrderedAscending;
            else
                return NSOrderedDescending;
            return NSOrderedSame;
        }];
        
    } else {
        sortSonglyarr= [self.currentSongsQueue sortedArrayUsingComparator:^(HSongItem * obj1 ,HSongItem* obj2) {
            if (obj1.syncid.doubleValue > obj2.syncid.doubleValue)
                return NSOrderedDescending;
            else
                return NSOrderedAscending;
            return NSOrderedSame;
        }];
    }

    
    [self.currentSongsQueue removeAllObjects];
    [self.currentSongsQueue addObjectsFromArray:sortSonglyarr];
    
    
//    if ([self.currentSongsQueue containsObject:self.currentPlaySongItem]) {
//        //NSLog(@"gsdsghdghshg");
//    }
    
    

}






@end
